import React, { Component } from "react";
import { connect } from "react-redux";
import lodash from "lodash";

// 组件
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";

import { Toast, InputItem } from "antd-mobile";

import yhTools from "@tools/yh";
import "./style.scss";
import { InterfaceG, agreements_url } from "@config/Config";
import Banner from "@/views/viewCommon/Banner";
import arrorwRight from "@images/paytool_right_icon.png";
import PaySkeleton from "@/component/skeleton/pay";
import { checkJumpPayResult } from "@/tools/xhf";
import XhfPaying from "@component/XhfPaying";
@connect(state => ({
	userId: state.getAppPlatformsDatas.userId,
	extJsonStr: state.getAppPlatformsDatas.extJsonStr
}))
class PayConfirm extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isSmsPay: true, // 是否是短信支付
			isSmsCount: false, // 是否倒计时
			countDownTime: 60, // 倒计时时间
			isSetPwd: true, // 是否设置支付密码
			preOrderData: {
				transAmount: "--"
			}, // 预下单信息
			password: "", // 支付密码
			smsCode: "", // 短信验证码
			isClickedSend: true, // 是否点击过发送验证码
			status: "-1",
			bannerList: [],
			paytoolsData: {},
			nowPaytool: {}, // 当前选中的支付方式
			verifyToken: ""
		};
		this.oldPaytool = {}; // 上一个支付方式
	}

	/*******************生命周期 start************************/
	componentDidMount() {
		let preOrder = this.preOrder();
		let getWalletBanner = this.getWalletBanner();
		let checkSetPassword = this.checkSetPassword();
		Promise.all([preOrder, getWalletBanner, checkSetPassword]).finally(() => {
			this.setState({
				status: 1
			});
			Toast.hide();
		});
	}
	/*******************生命周期 end************************/

	/*******************业务方法 start************************/
	/**
	 * @msg: 预下单
	 * @param {*}
	 * @return {*}
	 */
	preOrder() {
		const { query = {} } = this.props.location;
		return new Promise((resolve, reject) => {
			let { extJsonStr } = this.props;
			let extJsonObj = {};
			if (extJsonStr) {
				extJsonStr = extJsonStr.replace(
					/(?:\s*['"]*)?([a-zA-Z0-9]+)(?:['"]*\s*)?:/g,
					'"$1":'
				);
				extJsonObj = JSON.parse(extJsonStr);
			}
			console.log("extJsonStr--->", extJsonStr, extJsonObj);
			let lng = "",
				lat = "";
			if (extJsonObj.location) {
				lng = extJsonObj.location.lng;
				lat = extJsonObj.location.lat;
			}
			const objs = {
				url:
					query.from === "pageSytClickXhb"
						? InterfaceG.mmoney_pay_online_shenghuo_prepay_htqp
						: InterfaceG.mmoney_pay_online_shenghuo_prepay_htap,
				params: {
					userId: this.props.userId,
					longitude: lng,
					latitude: lat,
					payScene: query.payScene,
					channel: "05"
				}
			};
			yhTools.request(objs).then(res => {
				resolve();
				console.log("res", res);
				const { data, code, message } = res;
				if (code === "0") {
					this.setState({
						preOrderData: data
					});
				} else {
					// 通知生活支付结果
					yhTools.noticePayFailed(message);
				}
			});
		});
	}

	/**
	 * @msg: 获取banner
	 * @param {*}
	 * @return {*}
	 */
	getWalletBanner() {
		return new Promise((resolve, reject) => {
			let params = {
				url: InterfaceG.getBannerListByPageType,
				params: {
					pageType: "QUICK_SIGN_CONFIRM_PAY_PAGE"
				}
			};
			yhTools.request(params).then(res => {
				if (res.code === "0") {
					if (res.data && res.data.length > 0) {
						res.data.forEach(item => {
							if (item.bannerType == "QUICK_SIGN_CONFIRM_PAY_BOTTOM_BANNER") {
								this.setState({
									bannerList: item.indexServerDtos ? item.indexServerDtos : []
								});
							}
						});
					}
				}
				resolve();
			});
		});
	}

	/**
	 * @msg: 检查是否设置支付密码
	 * @param {*}
	 * @return {*}
	 */
	checkSetPassword() {
		return new Promise((resolve, reject) => {
			let objs = {
				url: InterfaceG.checkSetPassword,
				params: {},
				_alertShow: false
			};
			yhTools.request(objs).then(res => {
				resolve();
				if (res.code === "0") {
					this.setState({
						isSetPwd: true,
						isSmsPay: false
					});
				} else {
					this.setState({
						isSetPwd: false,
						isSmsPay: true
					});
				}
			});
		});
	}

	/**
	 * @msg: 短信倒计时
	 * @param {*}
	 * @return {*}
	 */
	countDown() {
		let { countDownTime } = this.state;
		this.setState({
			isSmsCount: true,
			isClickedSend: false
		});
		this.sendTimer = setInterval(() => {
			if (countDownTime < 1) {
				clearInterval(this.sendTimer);
				this.sendTimer = null;
				this.setState({
					countDownTime: 60,
					isSmsCount: false
				});
			} else {
				countDownTime--;
				this.setState({
					countDownTime
				});
			}
		}, 1000);
	}

	/**
	 * @msg: 短信支付发送短信
	 * @param {*}
	 * @return {*}
	 */
	sendVerifyCode() {
		const { preOrderData, transAmount } = this.state;
		const objs = {
			url: InterfaceG.mmoney_quickpay_send_verifyCode,
			params: {
				tradeNo: preOrderData.tradeNo,
				orderAmount: transAmount
			}
		};
		return yhTools.request(objs);
	}

	/**
	 * @msg: 确认支付
	 * @param {*}
	 * @return {*}
	 */
	confirmPay() {
		const {
			preOrderData,
			password,
			smsCode,
			isSmsPay,
			verifyToken
		} = this.state;
		const { query = {} } = this.props.location;
		if (!preOrderData) {
			// 通知生活支付结果
			yhTools.noticePayFailed("预下单失败，请重新发起");
			return;
		}
		if (isSmsPay && !this.checkSmsCode(smsCode)) {
			// 验证码校验失败
			return;
		}
		if (!isSmsPay && !this.checkPassword(password)) {
			// 密码校验失败
			return;
		}
		const objs = {
			url: InterfaceG.mmoney_password_confirm,
			params: {
				payTool: query.from === "pageSytClickXhb" ? "1004" : "1003",
				payScene: query.payScene,
				couponNo: "",
				outTradeNo: preOrderData.outTradeNo,
				tradeNo: preOrderData.tradeNo,
				verifyToken,
				password,
				smsCode,
				verifyType: isSmsPay ? "1" : "2" // 验密方式(1验证码(类型为验证码时smsCode不能为空) /2密码(类型为密码时password不能为空))
			}
		};
		Toast.info(XhfPaying(), 100);
		yhTools.request(objs).then(res => {
			const { code, message = "" } = res;
			Toast.hide();
			if (code === "0") {
				Toast.info("支付成功", 2);
				// 通知生活支付结果
				setTimeout(() => {
					//判断是否进入支付结果页
					const { tradeNo } = preOrderData;
					checkJumpPayResult({
						tradeNo,
						history: this.props.history
					});
				}, 2000);
				//11006编码不用关闭SDK
			} else if (code === "11006") {
				Toast.info(message, 2);
			} else {
				// 通知生活支付结果
				Toast.info(message, 2);
				setTimeout(() => {
					yhTools.noticePayFailed(message);
				}, 2000);
			}
		});
	}

	/**
	 * @msg: 检测密码正确性
	 * @param {*} password
	 * @return {*}
	 */
	checkPassword(password) {
		if (!password) {
			Toast.info("密码不能为空", 2);
			return false;
		}
		if (password.length != 6) {
			Toast.info("请输入六位支付密码", 2);
			return false;
		}
		return true;
	}

	/**
	 * @msg: 检测验证码正确性
	 * @param {*} smsCode
	 * @return {*}
	 */
	checkSmsCode(smsCode) {
		const { isClickedSend } = this.state;
		if (isClickedSend) {
			Toast.info("请先获取短信验证码", 2);
			return false;
		}
		if (!smsCode) {
			Toast.info("验证码不能为空", 2);
			return false;
		}
		return true;
	}

	/**
	 * @msg: 动态获取输入类型
	 * @param {*}
	 * @return {*}
	 */
	getInputType() {
		if (yhTools.platform() == "android") {
			return "number";
		}
		if (yhTools.platform() == "ios") {
			return "tel";
		}
	}

	/**
	 * @msg: 取消支付
	 * @param {*}
	 * @return {*}
	 */
	cancelOrder() {
		yhTools.noticePayCanceled("取消支付");
	}
	/*******************业务方法 end************************/

	/*******************点击事件 start************************/

	/**
	 * @msg: 切换支付方式
	 * @param {*}
	 * @return {*}
	 */
	changePaytoolClick() {
		let { isSmsPay } = this.state;
		this.setState({
			isSmsPay: !isSmsPay
		});
	}

	/**
	 * @msg: 点击确认支付
	 * @param {*}
	 * @return {*}
	 */
	confirmPayClick() {
		yhTools.debounceNew(this.confirmPay(), 200);
	}

	/**
	 * @msg: 点击发送验证码
	 * @param {*}
	 * @return {*}
	 */
	async sendVerifyCodeClick() {
		const { isSmsCount } = this.state;
		if (isSmsCount) {
			return;
		}
		Toast.info(XhfPaying(), 100);
		let res = await this.sendVerifyCode();
		const { code, data } = res;
		console.log("sendVerifyCodeClick--->", data);
		Toast.hide();
		if (code === "0") {
			this.setState({
				verifyToken: data.verifyToken
			});
			this.countDown(60);
			Toast.info(`已向您手机${data.mobileEncrypt}发送验证码`);
		} else if (code === "10000") {
			this.setState({
				verifyToken: data.verifyToken,
				isClickedSend: false
			});
			Toast.info(res.message, 2);
		} else {
			Toast.info(res.message, 2);
		}
	}

	/**
	 * @msg: 密码输入改变
	 * @param {*} e 事件对象
	 * @return {*}
	 */
	inputChange(e) {
		let value = e.target.value;
		if (e.target.value.length > 6) {
			value = e.target.value.slice(0, 6);
		}
		this.setState(
			{
				password: value
			},
			() => {
				if (value.length === 6) {
					document.activeElement.blur();
				}
			}
		);
	}

	/**
	 * @msg: 点击选券
	 * @param {*}
	 * @return {*}
	 */
	selectCouponClick() {
		this.props.history.push("/selectCouponForH5");
	}

	/**
	 * @msg: 验证码输入
	 * @param {*} v
	 * @return {*}
	 */
	smsCodeChange(v) {
		if (v && v.length === 6) {
			document.activeElement.blur();
		}
		this.setState({
			smsCode: v
		});
	}

	/**
	 * @msg: 切换支付方式
	 * @param {*} item
	 * @return {*}
	 */
	changePaytool = item => {
		this.setState({
			nowPaytool: item
		});
	};
	/*******************点击事件 end************************/

	/**渲染 */
	render() {
		const {
			isSetPwd,
			isSmsPay,
			isSmsCount,
			countDownTime,
			preOrderData,
			password,
			isClickedSend,
			status,
			bannerList,
			paytoolsData = {},
			nowPaytool
		} = this.state;
		const { selectedCoupon } = this.props;
		const { payToolBos = [] } = paytoolsData;

		const _pageParams = {
			header: {
				title: "支付确认",
				goBackAction: () => {
					this.cancelOrder();
				}
			},
			componentDidRecover: () => {
				// 缓存
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="page-payConfirm">
					<PaySkeleton load={status === "-1"}>
						<div className="wallet-box">
							{/* 头部 */}
							<section className="wallet-top_content">
								<p className="shop-name">订单金额</p>
								<p className="unit">
									¥<span className="pay-money">{preOrderData.transAmount}</span>
								</p>
							</section>
							{/* 详情 */}
							<section className="wallet-detail_content">
								<div className="wallet-detail-item">
									<div className="item-left">支付优惠</div>
									{selectedCoupon ? (
										<div
											onClick={this.selectCouponClick.bind(this)}
											className="item-right red"
										>
											<div className="money">
												-¥{selectedCoupon.couponValue}
											</div>
											<img src={arrorwRight} className="arrorw-img" />
										</div>
									) : (
										<div className="item-right">暂无</div>
									)}
								</div>
								<div
									className="wallet-detail-item"
									style={{ borderBottomWidth: "0px" }}
								>
									<div className="item-left">支付活动</div>
									<div className="item-right">暂无</div>
								</div>

								<div className="wallet-detail-item paytool-box">
									<div className="item-left">
										{!isSmsPay ? "密码支付" : "验证码支付"}
										{isSetPwd && (
											<span
												className="change-input"
												onClick={this.changePaytoolClick.bind(this)}
											>
												｜ 切换
												{isSmsPay ? "密码支付" : "验证码支付"}
											</span>
										)}
									</div>
								</div>
							</section>

							{!isSmsPay && (
								<section className="wallet-input-box">
									<div className="wallet-pwd_input-box">
										<input
											className="pwd-input"
											value={password}
											type={this.getInputType()}
											pattern="[0-9]"
											maxLength={6}
											onChange={e => {
												this.inputChange(e);
											}}
										/>
										{["", "", "", "", "", ""].map((item, index) => {
											return password && password.split("")[index] ? (
												<div key={index} className="input-item">
													.
												</div>
											) : (
												<div key={index} className="input-item"></div>
											);
										})}
									</div>
								</section>
							)}
							{isSmsPay && (
								<section className="wallet-input-box">
									<div className="wallet-sms_input-box">
										<InputItem
											clear
											placeholder="请输入验证码"
											maxLength={6}
											minLength={6}
											pattern="[0-9]{6}"
											type="tel"
											className="sms-input"
											onChange={this.smsCodeChange.bind(this)}
											extra={
												<div
													className={
														isSmsCount ? "send-code send" : "send-code"
													}
												>
													{isClickedSend
														? "发送"
														: isSmsCount
														? `重发${countDownTime}s`
														: "重发"}
												</div>
											}
											onExtraClick={lodash.throttle(
												this.sendVerifyCodeClick.bind(this),
												2000,
												{ trailing: false }
											)}
										></InputItem>
									</div>
								</section>
							)}
							<Button
								className="payConfirm-btn"
								onClick={this.confirmPayClick.bind(this)}
								buttonStyle={{
									height: "1rem",
									lineHeight: "1rem",
									borderRadius: "0.5rem"
								}}
							>
								确认支付
							</Button>
							{bannerList && bannerList.length > 0 && (
								<Banner bannerList={bannerList} history={this.props.history} />
							)}
						</div>
					</PaySkeleton>
				</div>
			</MainLayout>
		);
	}
}

export default PayConfirm;
